#pragma once
#include <iostream>
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
 
namespace Server
{
    using namespace std;
    const static string defaultIP = "0.0.0.0";
    enum {USAGE_ERR = 1, SOCKET_ERR, BIND_ERR,OPEN_ERR};
    typedef function<void(int,string,uint16_t,string)> func_t;
    class udpServer
    {
    public:
        udpServer(const func_t& cb,uint16_t port, const string &ip = defaultIP) 
        :_callback(cb),_port(port),_ip(ip),_sockfd(-1)
        {}
        void initServer()
        {
            _sockfd = socket(AF_INET,SOCK_DGRAM,0);
            if(_sockfd == -1)
            {
                cerr<<"socket error:" << errno << strerror(errno) << endl;
                exit(SOCKET_ERR);
            }
            struct sockaddr_in local;
            bzero(&local,sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            int n = bind(_sockfd,(struct sockaddr*)&local,sizeof(local));
            if(n == -1)
            {
                cerr<<"bind error:" << errno << strerror(errno) << endl;
                exit(BIND_ERR);
            }
        }
        void startServer()
        {
            char buffer[1024];
            for(;;)
            {
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                ssize_t s = recvfrom(_sockfd,buffer,sizeof(buffer)-1,0,(struct sockaddr*)&peer,&len);
                if(s)
                {
                    buffer[s] = { 0 };
                    string clientIp = inet_ntoa(peer.sin_addr);
                    uint16_t clientPort = ntohs(peer.sin_port);
                    string message = buffer;
                    cout << clientIp << "[" << clientPort << "]" << message << endl;
                    //服务器只负责接受数据，处理方法采用回调的方式交给上层处理
                    _callback(_sockfd,clientIp,clientPort,message);
                }
            }
        }
        ~udpServer()
        {}
    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
        func_t _callback;
    };
}